package org.onejava.db.mapping;

import java.sql.Connection;
import java.sql.SQLException;

import org.onejava.db.DbcpConnection;
import org.onejava.db.transaction.TransactionEntity;

/**
 * 增强事务SQL处理类
 * 实现了事务Entity的计数器，可以处理更为复杂的嵌套式事务
 * @author frost
 *
 */
public class TransactionMapping extends SqlMapping {
	private static class SingletonHolder{
		private static TransactionMapping instance = new TransactionMapping();
	}
	
	private TransactionMapping(){
	}
	
	public static TransactionMapping getInstance() {
		return SingletonHolder.instance;
		
	}
	
	/**
	 *  开启事务，如果事务已存在，则事务计数器加一
	 *  
	 */
	public boolean startTran()throws Exception{
		if(TRANSACTION_ENTITY.get()==null){
			TRANSACTION_ENTITY.set(createTransactionEntity(0));
			try {
				getConn().setAutoCommit(false);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				closeSou();
				throw new Exception(e);
			}
		}else{
			TRANSACTION_ENTITY.get().addCount();
		}
		return true;
	}
	
	/* (non-Javadoc)
	 * @see org.onejava.db.BaseSqlMapping#closeSou()
	 */
	public void closeSou() throws Exception{
		if(getConn()!= null&&!getConn().isClosed()){ 
				getConn().close();
				TRANSACTION_ENTITY.remove();
		}
		log.info("数据库资源关闭");
	}
	
	/* (non-Javadoc)
	 * @see org.onejava.db.BaseSqlMapping#runCommit()
	 */
	public  void   runCommit() throws Exception{
		if(TRANSACTION_ENTITY.get().getCount()>0){
			//事务不需要提交，计数器减一
			TRANSACTION_ENTITY.get().subCount();
		}else{
			//计数器为0，事务提交
			try {
				getConn().commit();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				throw new Exception(e);
			}finally{
				closeSou();
			}
		}
	}
	/**
	 * 事务的回滚
	 * @throws Exception 
	 */
	public  void  runRollBack() throws Exception{
		try {
			getConn().rollback();
		} catch (SQLException e) {
			throw new Exception(e);
		}finally{
			log.info("事务回滚了");
			closeSou();
		}
	}
	
	private Connection getConn(){
		return getEntity().getConn();
	}
	
	private TransactionEntity getEntity(){
		return TRANSACTION_ENTITY.get();
		
	}
	
	/**
	 * 创建一个新的 createTransactionEntity
	 * 初始化计数器为0
	 * @return TransactionEntity
	 * @throws Exception 
	 */
	
	private TransactionEntity createTransactionEntity(int type) throws Exception{
		return new TransactionEntity(type, DbcpConnection.getConnection(), 0);
	}
}
